﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Navigation;
using BlogApp.Data.Models;
using BlogApp.WP8.ViewModel;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Practices.ServiceLocation;
using GestureEventArgs = System.Windows.Input.GestureEventArgs;

namespace BlogApp.WP8.View
{
    public partial class SearchPage : PhoneApplicationPage
    {
        private SearchViewModel _vm;
        

        public SearchPage()
        {
            InitializeComponent();

            _vm = (SearchViewModel) DataContext;
        }


        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode != NavigationMode.Back)
            {
                _vm.Cleanup();
            }

            var categoryParameter = string.Empty;
            NavigationContext.QueryString.TryGetValue("category", out categoryParameter);

            if (!string.IsNullOrEmpty(categoryParameter))
            {
                _vm.SearchInActiveCategory = true;
            }

            
            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            //_vm.Cleanup();
            base.OnNavigatedFrom(e);
        }

        private void OnArticleTapped(object sender, GestureEventArgs e)
        {
            var post = (Post) ((StackPanel) sender).DataContext;
            ServiceLocator.Current.GetInstance<PostViewModel>().OpenBlogPostCommand.Execute(post);

            Debug.WriteLine("SearchPage.xaml.cs | OnArticleTapped | PostId: {0}", post.Id);

            //var post = (Post)((StackPanel)sender).DataContext;
            //ServiceLocator.Current.GetInstance<MainViewModel>().OpenBlogPostCommand.Execute(post);

            //Debug.WriteLine("SearchPage.xaml.cs | OnArticleTapped | PostId: {0}", post.Id);
        }

        private void SearchQuery_OnKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                _vm.SearchPostWithQuery.Execute(searchQuery.Text);
            }
        }
    }
}